package eu.webhib.frmwrk.utils;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.log4j.Logger;

public class MailUtils {

   private static final Logger log = Logger.getLogger(MailUtils.class);
   //
   private static ExtendedProperties prop = null;

   public static void setProperties(ExtendedProperties initProp) {
      log.info("setProperties");
      prop = initProp;
   }

   public static boolean sendMail(String toEmailAddr, String subject, String mailContent) {
      try {
         sendMailSmtp(prop, prop.get("mail.from"), toEmailAddr, subject, mailContent);
         return true;
      } catch (MessagingException ex) {
         log.error("sendMail error", ex);
         return false;
      }
   }

   private static void sendMailSmtp(final ExtendedProperties props, String fromEmailAddr, String toEmaiAddr,
           String subject, String mailContent) throws MessagingException {

      log.info("sendMailSmtp");
      //
      Session session = Session.getInstance(props, new javax.mail.Authenticator()     {

         @Override
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.user"), props.get("mail.smtp.password"));
         }
      });
      session.setDebug(props.getBoolean("mail.debug", false));

      Message msg = new MimeMessage(session);
      //
      log.info("sent from: " + fromEmailAddr);
      InternetAddress addressFrom = new InternetAddress(fromEmailAddr);
      msg.setFrom(addressFrom);
      InternetAddress addressTo = new InternetAddress(toEmaiAddr);
      msg.setRecipient(Message.RecipientType.TO, addressTo);
      //
      msg.setSubject(subject);
      //msg.setContent(mailContent, "text/plain");
      msg.setText(mailContent);
      Transport.send(msg);
      log.info ("sent to:  " + toEmaiAddr);
      log.debug("Subject:  " + subject);
      log.debug("Content:  " + mailContent);
   }

   public static boolean receiveMails() {
      try {
         receiveMailsSmtp(prop);
         return true;
      } catch (Exception ex) {
         log.error("receiveMails error", ex);
         return false;
      }
   }

   private static void receiveMailsSmtp(final ExtendedProperties props) throws Exception {

      log.info("receiveMailsSmtp");
      //
      Session session = Session.getInstance(props, new javax.mail.Authenticator()     {

         @Override
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.pop3.user"), props.get("mail.pop3.password"));
         }
      });
      session.setDebug(props.getBoolean("mail.debug", false));

      Store store = session.getStore("pop3");
      store.connect();

      Folder folder = store.getFolder("INBOX");
      folder.open(Folder.READ_WRITE);

      log.info("Number of messages received: " + folder.getMessageCount());

      Message message[] = folder.getMessages();
      for (int i = 0; i < message.length; i++) {
         Message m = message[i];
         log.info ("Message: " + i);
         log.info ("From:         " + Arrays.toString(m.getFrom()));
         log.debug("Subject       " + m.getSubject());
         log.debug("Send at:      " + m.getSentDate());
         log.debug("Content-Type: " + new ContentType(m.getContentType()));
         if (m.isMimeType("text/plain")) {
            log.debug(m.getContent());
         }
         m.setFlag(Flags.Flag.DELETED, true);
      }
      folder.close(true);
      store.close();
   }
}
